<template>
    <div class="bill_baohutong">
        <!-- 查询 -->
        <div class="zw-form-layout">
            <el-form ref="formRef" :model="form" label-width="auto">
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="分账方信息" prop="split_keywords">
                            <el-input
                                v-model.trim="form.split_keywords"
                                clearable
                                placeholder="请输入商户名称/账号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="分账接收方信息" prop="split_receiver_keywords">
                            <el-input
                                v-model.trim="form.split_receiver_keywords"
                                clearable
                                placeholder="请输入商户名称/账号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-show="defaultExpand">
                        <el-form-item label="分账结果" prop="status">
                            <el-select v-model="form.status" placeholder="全部结果" clearable>
                                <el-option
                                    v-for="item in mainType"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-show="defaultExpand">
                        <el-form-item label="分账发起时间" prop="created_at">
                            <el-date-picker
                                v-model="form.created_at"
                                type="daterange"
                                clearable
                                :default-time="defaultTime"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="defaultExpand ? 16 : 8" class="zw-form-btns">
                        <el-button type="primary" @click="searchHandler">查询</el-button>
                        <el-button plain class="btn-reset" @click="resetHandler">清空</el-button>
                        <el-button v-if="defaultExpand" class="icon_btn" text type="primary" @click="handleExpand">
                            收起<el-icon><ArrowUp /></el-icon>
                        </el-button>
                        <el-button v-else class="icon_btn" :text="true" type="primary" @click="handleExpand">
                            展开<el-icon><ArrowDown /></el-icon>
                        </el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="bill_baohutong_bottom" :class="{ bill_baohutong_bottom_expand: !defaultExpand }">
            <!-- 列表 -->
            <el-table
                ref="tableRef"
                :data="tableList"
                :height="tableHeight"
                type="expand"
                :default-expand-all="true"
                row-key="id"
                v-loading="loading"
                :row-class-name="getClass"
                :class="{ 'el-table-empty': !tableList?.length }">
                <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                    <template #default="{ row }">
                        <template v-if="prop === 'split_account_name' || prop === 'split_receiver_name'">
                            <div class="corp-name">
                                <div class="corp-name-main">
                                    <ZwTooltip :content="row[prop]" :line="2" />
                                </div>
                                <div class="corp-name-sub">
                                    <ZwTooltip :content="row[SUB_KEY[prop]] + '：' + row[NO_KEY[prop]]" />
                                </div>
                            </div>
                        </template>
                        <template v-if="prop === 'status_name'">
                            <span
                                class="custom-status-point"
                                :style="{ '--status-bgcolor': StatusColorOption[row.status] || '#60B900' }">
                                {{ row.status_name || '--' }}
                                <ZwTooltip
                                    v-if="row.status === 'FAILED'"
                                    type="icon"
                                    icon-src="https://img.static-keyid.cn/toolspace/scrm/2023/10/1698393880933li5mnptqtz5pzw3g.png"
                                    :content="row.remark" />
                            </span>
                        </template>
                        <template v-if="prop === 'split_amount'">
                            <span>{{ Number(row.split_amount || 0).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}</span>
                        </template>
                    </template>
                </el-table-column>
                <template #empty>
                    <div class="table-empty">
                        <img
                            src="https://img.static-keyid.cn/toolspace/scrm/2023/10/1697683499137ngcb4fpdwjr9ijb4.png" />
                        <div>暂无数据</div>
                    </div>
                </template>
            </el-table>
            <!-- 分页 -->
            <Pagination
                class="custom-bottom-page"
                :total="totalCount"
                :page-size="form.page_size"
                :current-page="form.page"
                @sizeChange="changeSizeHandler"
                @pageChange="changePageHandler" />
        </div>
    </div>
</template>

<script setup name="divisionBill">
import { ref, reactive, computed, onActivated, onDeactivated, nextTick } from 'vue';
import request from '@/request/index';
import constants from '@/commons/constants';
import { packSelectObjUtil, cloneDeep } from '@/commons/utils';
import { setLayout, resetLayout, resizeTableHeight, getTableHeight, resizeTableRemove } from '@/hooks/layout';
import Pagination from '@/components/Pagination.vue';
import ZwTooltip from '@/components/ZwTooltip.vue';

const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]; // 默认日期
const mainType = reactive(packSelectObjUtil(constants.DISTRIBUTION_RESULT, false)); // 分账结果

const form = reactive({
    page: 1, //页码数
    page_size: 10, //每页显示数
    split_keywords: '', // 分账方信息
    split_receiver_keywords: '', // 分账接收方信息
    status: null, // 分账结果 INIT初始化 PROCESS 处理中 SUCCESS成功 FAILED失败
    created_at: [] //创建时间
}); // 查询表单
let formClone = cloneDeep(form); // 查询备份
const formRef = ref(null); // form ref
const tableRef = ref(null);
const totalCount = ref(0); // 数据总数
const tableList = reactive([]); // 表格数据
let defaultExpand = ref(true); // 展开/收起

// 控制查询展开收起
const handleExpand = () => {
    defaultExpand.value = !defaultExpand.value;
    setTimeout(() => {
        getTableHeight('bill_baohutong_bottom', tableHeight, 'custom-bottom-page');
    });
};

// 进度状态颜色
const StatusColorOption = {
    FAILED: '#E93C3F',
    PROCESS: '#4DA2E7',
    SUCCESS: '#60B900'
};

const tableColumns = computed(() => {
    const baseTableColumns = [
        { label: '分账方信息', prop: 'split_account_name', minWidth: '280' },
        { label: '分账金额（元）', prop: 'split_amount', minWidth: '140' },
        { label: '分账结果', prop: 'status_name', minWidth: '140' },
        { label: '分账接收方信息', prop: 'split_receiver_name', minWidth: '280' },
        { label: '分账发起时间', prop: 'created_at', minWidth: '170' }
    ];
    return baseTableColumns;
});

const NO_KEY = {
    split_account_name: 'split_merchant_no',
    split_receiver_name: 'receiver_merchant_no'
};
const SUB_KEY = {
    split_account_name: 'split_isv_code_name',
    split_receiver_name: 'receiver_isv_code_name'
};
// 获取行class
const getClass = ({ row }) => {
    if (row.status != 10 && row?.isp_info?.length) {
        return 'not-border';
    }
};

// 以下有时间抽离成公共查询js
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    formClone.page = form.page;
    queryListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.page_size = perPage;
    formClone.page = form.page;
    formClone.page_size = form.page_size;
    queryListHandler();
};

/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    searchHandler();
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    formClone = cloneDeep(form);
    queryListHandler();
};

/**
 * 分页查询
 */
const loading = ref(false);
const queryListHandler = async notScroll => {
    loading.value = true;
    const _form = cloneDeep(formClone);
    const res = await request('splitAccountBillListServ', _form);
    loading.value = false;
    const list = (res?.data?.data || [])?.map(item => {
        return item;
    });
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = res.data.total;
    nextTick(() => {
        // 加载数据后将table滚动条滚动到table最顶部和最左边
        !notScroll && tableRef?.value?.scrollTo(0, 0);
    });
};

// 页面可见监听函数
const visibilitychange = () => {
    if (document.visibilityState === 'visible') {
        queryListHandler();
    }
};

const getAllData = () => {
    queryListHandler();
};

let tableHeight = ref(300);
onActivated(() => {
    Object.keys(formClone || {})?.forEach(key => {
        form[key] = formClone[key];
    });
    getAllData();
    setLayout('bill-baofutong-layout');
    setTimeout(() => {
        resizeTableHeight('bill_baohutong_bottom', tableHeight, 'custom-bottom-page');
    }, 0);

    // useDocumentVisibility('add', visibilitychange);
});
onDeactivated(() => {
    resetLayout('bill-baofutong-layout');
    resizeTableRemove();
    // useDocumentVisibility('remove', visibilitychange);
});
</script>
<style lang="scss">
.bill-baofutong-layout {
    height: 100%;
    padding: 0 !important;
    background-color: #f3f3f3 !important;
}
</style>
<style lang="scss" scoped>
@import './scss/index.scss';
</style>
